package cn.wolfcode.exception;

import cn.wolfcode.qo.JsonResult;
import com.alibaba.fastjson.JSON;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletResponse;

@ControllerAdvice
public class ControllerAdviceForException {

    @ExceptionHandler(RuntimeException.class)
    public Object handlerException(Model model,RuntimeException e, HttpServletResponse response, HandlerMethod method) {
        e.printStackTrace();  //输出异常
        //判断异常的方法是否贴有RespnseBody注解
        if (method.hasMethodAnnotation(ResponseBody.class)) {
            //利用响应对象输出json对象
            response.setContentType("applicationContext/json;charset=utf-8");
            JsonResult json = new JsonResult(false, "操作失败,请联系管理员");
            try {
                System.out.println(JSON.toJSONString(json));
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            return null;
        } else {
            model.addAttribute("ex",e);
            return "common/error";
        }
    }

    /**
     * 捕获没有权限的异常
     * @param model
     * @param e
     * @param response
     * @param method
     * @return
     */
    @ExceptionHandler(UnauthorizedException.class)
    public Object UnauthorizedException(Model model,RuntimeException e, HttpServletResponse response, HandlerMethod method) {
        //判断异常的方法是否贴有RespnseBody注解
        if (method.hasMethodAnnotation(ResponseBody.class)) {
            //利用响应对象输出json对象
            response.setContentType("applicationContext/json;charset=utf-8");
            JsonResult json = new JsonResult(false, "操作失败,请联系管理员");
            try {
                System.out.println(JSON.toJSONString(json));
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            return null;
        } else {
            model.addAttribute("ex",e);
            return "common/nopermission";
        }
    }

    /**
     * 禁用账号
     * @return
     */
    @ExceptionHandler(AuthenticationException.class)
    @ResponseBody
    public Object AuthenticationException() {
        return new JsonResult(false,"你的账号被禁用");
    }


}
